package be.idamf.flash.events
{
	import be.idamf.flash.exec.deferExec;
	
	import flash.events.Event;
	
	import org.flexunit.asserts.*;
	import org.flexunit.async.Async;

	public class REventDispatcherTest
	{
		public static const TYPE:String = "test";

		public var dispatcher:IREventDispatcher;
		public var listener:Listener;
		public var flag:Boolean;

		public function REventDispatcherTest()
		{
		}

		[Before]
		public function setUp():void
		{
			dispatcher = new REventDispatcher();
			listener = new Listener(this);
			flag = false;
		}

		[After]
		public function tearDown():void
		{
			dispatcher = null;
			listener = null;
		}

		protected function dispatchEvent():void
		{
			dispatcher.dispatchEvent(new Event(TYPE));
		}

		protected function addStrong():void
		{
			dispatcher.addEventListener(TYPE, listener.handler);
		}

		protected function addWeakUnCollected():void
		{
			dispatcher.addWeakEventListener(TYPE, listener, "handler");
		}

		protected function addWeakCollected():void
		{
			dispatcher.addWeakEventListener(TYPE, new Listener(this), "handler");
		}

		[Test]
		public function testStrong():void
		{
			addStrong();
			dispatchEvent();
			assertTrue(flag);
		}

		[Test]
		public function testWeakUnCollected():void
		{
			addWeakUnCollected();
			dispatchEvent();
			assertTrue(flag);
		}

		[Test(async)]
		public function testWeakCollected():void
		{
			addWeakCollected();
			deferExec(this, Async.asyncHandler(this, continue_testWeakCollected, 1000), true, null);
		}

		public function continue_testWeakCollected(event:Event, passThroughData:Object):void
		{
			dispatchEvent();
			assertFalse(flag);
		}

		[Test]
		public function testRemoveStrong():void
		{
			addStrong();
			dispatcher.removeEventListener(TYPE, listener.handler);
			dispatchEvent();
			assertFalse(flag);
		}

		[Test]
		public function testRemoveWeakUnCollected():void
		{
			addWeakUnCollected();
			dispatcher.removeEventListener(TYPE, listener.handler);
			dispatchEvent();
			assertFalse(flag);
		}

		[Test]
		public function testRemoveAll():void
		{
			addStrong();
			addWeakUnCollected();
			dispatcher.removeAllEventListeners();
			dispatchEvent();
			assertFalse(flag);
		}
	}
}

import flash.events.Event;
import be.idamf.flash.events.REventDispatcherTest;

internal class Listener
{
	protected var test:REventDispatcherTest;

	public function Listener(test:REventDispatcherTest)
	{
		this.test = test;
	}

	public function handler(event:Event):void
	{
		test.flag = true;
	}
}
